import express from 'express'
import { authenticateToken } from '../middleware/auth.js'
import { upload } from '../middleware/upload.js'
import db, { generateId } from '../db/database.js'
import {
  recognizeIdCardFront,
  recognizeIdCardBack,
  compareFace,
  imageUrlToBase64,
  validateIdCard,
} from '../services/tencent-cloud.js'
import fs from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const router = express.Router()

/**
 * 提交实名认证
 * POST /api/identity/verify
 * 需要上传：身份证正面、身份证反面、人脸照片
 */
router.post('/verify', authenticateToken, upload.fields([
  { name: 'idCardFront', maxCount: 1 },
  { name: 'idCardBack', maxCount: 1 },
  { name: 'faceImage', maxCount: 1 },
]), async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { realName, idCardNumber } = req.body

    // 验证必填字段
    if (!realName || !idCardNumber) {
      return res.status(400).json({
        code: 400,
        message: '请提供真实姓名和身份证号码',
        success: false,
      })
    }

    // 验证身份证号码格式
    if (!validateIdCard(idCardNumber)) {
      return res.status(400).json({
        code: 400,
        message: '身份证号码格式不正确',
        success: false,
      })
    }

    // 检查文件
    const files = req.files
    if (!files || !files.idCardFront || !files.idCardBack || !files.faceImage) {
      return res.status(400).json({
        code: 400,
        message: '请上传身份证正面、反面和人脸照片',
        success: false,
      })
    }

    // 检查是否已经提交过认证
    const existing = db.prepare('SELECT * FROM identity_verifications WHERE user_id = ?').get(userId)
    if (existing && existing.verification_status !== 'rejected') {
      return res.status(400).json({
        code: 400,
        message: '您已经提交过实名认证，请等待审核',
        success: false,
      })
    }

    // 读取图片文件并转换为Base64
    const idCardFrontPath = files.idCardFront[0].path
    const idCardBackPath = files.idCardBack[0].path
    const faceImagePath = files.faceImage[0].path

    const idCardFrontBase64 = fs.readFileSync(idCardFrontPath).toString('base64')
    const idCardBackBase64 = fs.readFileSync(idCardBackPath).toString('base64')
    const faceImageBase64 = fs.readFileSync(faceImagePath).toString('base64')

    // 调用腾讯云OCR识别身份证
    let ocrResult
    try {
      ocrResult = await recognizeIdCardFront(idCardFrontBase64)
    } catch (error) {
      // 清理上传的文件
      [idCardFrontPath, idCardBackPath, faceImagePath].forEach(path => {
        if (fs.existsSync(path)) fs.unlinkSync(path)
      })
      return res.status(400).json({
        code: 400,
        message: `身份证识别失败: ${error.message}`,
        success: false,
      })
    }

    // 验证OCR识别的姓名和身份证号码是否与用户输入一致
    const ocrName = ocrResult.data.name
    const ocrIdCard = ocrResult.data.idCard

    if (ocrName !== realName) {
      return res.status(400).json({
        code: 400,
        message: `姓名不匹配，识别到的姓名为: ${ocrName}`,
        success: false,
      })
    }

    if (ocrIdCard !== idCardNumber) {
      return res.status(400).json({
        code: 400,
        message: `身份证号码不匹配，识别到的号码为: ${ocrIdCard}`,
        success: false,
      })
    }

    // 识别身份证反面
    let backResult
    try {
      backResult = await recognizeIdCardBack(idCardBackBase64)
    } catch (error) {
      console.error('身份证反面识别失败:', error)
      // 反面识别失败不影响主流程，继续执行
    }

    // 人脸比对
    let faceCompareResult
    try {
      faceCompareResult = await compareFace(idCardFrontBase64, faceImageBase64)
    } catch (error) {
      // 清理上传的文件
      [idCardFrontPath, idCardBackPath, faceImagePath].forEach(path => {
        if (fs.existsSync(path)) fs.unlinkSync(path)
      })
      return res.status(400).json({
        code: 400,
        message: `人脸比对失败: ${error.message}`,
        success: false,
      })
    }

    // 检查人脸相似度
    if (!faceCompareResult.data.matched) {
      return res.status(400).json({
        code: 400,
        message: `人脸相似度不足，相似度: ${faceCompareResult.data.score}，要求: ${faceCompareResult.data.threshold}`,
        success: false,
      })
    }

    // 保存文件路径（相对于uploads目录）
    const idCardFrontUrl = `/uploads/${files.idCardFront[0].filename}`
    const idCardBackUrl = `/uploads/${files.idCardBack[0].filename}`
    const faceImageUrl = `/uploads/${files.faceImage[0].filename}`

    // 保存到数据库
    const verificationId = generateId()
    const now = new Date().toISOString()

    if (existing) {
      // 更新现有记录
      db.prepare(`
        UPDATE identity_verifications
        SET real_name = ?, id_card_number = ?, id_card_front_url = ?, id_card_back_url = ?,
            face_image_url = ?, verification_status = 'processing', rejection_reason = NULL,
            tencent_request_id = ?, tencent_result = ?, face_compare_score = ?,
            updated_at = ?
        WHERE user_id = ?
      `).run(
        realName,
        idCardNumber,
        idCardFrontUrl,
        idCardBackUrl,
        faceImageUrl,
        ocrResult.requestId,
        JSON.stringify({ ocr: ocrResult, back: backResult, faceCompare: faceCompareResult }),
        faceCompareResult.data.score,
        now,
        userId
      )
    } else {
      // 插入新记录
      db.prepare(`
        INSERT INTO identity_verifications (
          id, user_id, real_name, id_card_number, id_card_front_url, id_card_back_url,
          face_image_url, verification_status, tencent_request_id, tencent_result, face_compare_score,
          created_at, updated_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, 'processing', ?, ?, ?, ?, ?)
      `).run(
        verificationId,
        userId,
        realName,
        idCardNumber,
        idCardFrontUrl,
        idCardBackUrl,
        faceImageUrl,
        ocrResult.requestId,
        JSON.stringify({ ocr: ocrResult, back: backResult, faceCompare: faceCompareResult }),
        faceCompareResult.data.score,
        now,
        now
      )
    }

    // 自动审核通过（如果相似度足够高）
    let finalStatus = 'processing'
    if (faceCompareResult.data.score >= 90) {
      finalStatus = 'approved'
      db.prepare(`
        UPDATE identity_verifications
        SET verification_status = 'approved', verified_at = ?
        WHERE user_id = ?
      `).run(now, userId)
    }

    res.json({
      code: 200,
      message: '实名认证提交成功',
      success: true,
      data: {
        verificationId,
        status: finalStatus,
        faceScore: faceCompareResult.data.score,
        message: finalStatus === 'approved' 
          ? '认证已自动通过' 
          : '认证已提交，等待人工审核',
      },
    })
  } catch (error) {
    console.error('实名认证错误:', error)
    next(error)
  }
})

/**
 * 获取实名认证状态
 * GET /api/identity/status
 */
router.get('/status', authenticateToken, async (req, res, next) => {
  try {
    const userId = req.user.userId

    const verification = db.prepare(`
      SELECT id, real_name, id_card_number, verification_status, rejection_reason,
             face_compare_score, created_at, updated_at, verified_at
      FROM identity_verifications
      WHERE user_id = ?
    `).get(userId)

    if (!verification) {
      return res.json({
        code: 200,
        message: '获取成功',
        success: true,
        data: {
          verified: false,
          status: null,
        },
      })
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        verified: true,
        status: verification.verification_status,
        realName: verification.real_name,
        idCardNumber: verification.id_card_number ? 
          verification.id_card_number.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') : null, // 脱敏显示
        faceScore: verification.face_compare_score,
        rejectionReason: verification.rejection_reason,
        createdAt: verification.created_at,
        updatedAt: verification.updated_at,
        verifiedAt: verification.verified_at,
      },
    })
  } catch (error) {
    next(error)
  }
})

/**
 * 管理员审核实名认证
 * POST /api/identity/approve
 */
router.post('/approve', authenticateToken, async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { verificationId, action, reason } = req.body

    // TODO: 这里应该检查用户是否有管理员权限
    // 暂时简化处理

    if (!verificationId || !action) {
      return res.status(400).json({
        code: 400,
        message: '请提供认证ID和操作类型',
        success: false,
      })
    }

    if (!['approved', 'rejected'].includes(action)) {
      return res.status(400).json({
        code: 400,
        message: '操作类型必须是 approved 或 rejected',
        success: false,
      })
    }

    if (action === 'rejected' && !reason) {
      return res.status(400).json({
        code: 400,
        message: '拒绝时必须提供原因',
        success: false,
      })
    }

    const now = new Date().toISOString()

    if (action === 'approved') {
      db.prepare(`
        UPDATE identity_verifications
        SET verification_status = 'approved', verified_at = ?, updated_at = ?, rejection_reason = NULL
        WHERE id = ?
      `).run(now, now, verificationId)
    } else {
      db.prepare(`
        UPDATE identity_verifications
        SET verification_status = 'rejected', rejection_reason = ?, updated_at = ?
        WHERE id = ?
      `).run(reason, now, verificationId)
    }

    res.json({
      code: 200,
      message: action === 'approved' ? '认证已通过' : '认证已拒绝',
      success: true,
    })
  } catch (error) {
    next(error)
  }
})

export default router






